package com.zengqingfa.shardingjdbc.demo.sharding.precise;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 *
 * @fileName: ShardingTablePreciseAlgorithm
 * @author: zengqf3
 * @date: 2021-3-28 21:40
 * @description: 分表算法
 */
@Slf4j
public class ShardingTablePreciseAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        log.info("Precise table collection:" + JSON.toJSONString(availableTargetNames) + ",shardingValue:" + JSON
                .toJSONString(shardingValue));
        String value = shardingValue.getValue();
        long tenant_code_mod = Math.abs(value.hashCode() / 2 % 3 + 1);
        for (String availableTargetName : availableTargetNames) {
            if (availableTargetName.endsWith(String.format("%02d", tenant_code_mod))) {
                return availableTargetName;
            }
        }
        throw new UnsupportedOperationException();
    }
}
